<template>
    <el-container class="layout-container">
        <div class="wrap" v-loading="loading">
            <el-scrollbar>

            <el-row :gutter="20" class="row">
                <el-col class="col" :span="item.col" v-for="item in card">
                    <div class="card-wrap">
                        <m-card :show-yesterday="item.showYesterday" :options="item" :data="cardData[item.field_id]"></m-card>
                    </div>
                </el-col>
            </el-row>
            <el-row :gutter="20" class="row">
                <el-col :span="24">
                    <div class="chart-wrap" v-loading="chartLoading">
                        <div class="tool-wrap" style="display: flex;">
                            <el-radio-group class="radio-wrap" v-model="salesRadio" @change="handleRadioChange">
                                <el-radio-button label="今天" />
                                <el-radio-button label="本周" />
                                <el-radio-button label="本月" />
                                <el-radio-button label="本季" />
                            </el-radio-group>
                            <!--<div class="date-wrap"><m-form :fields="salesDate" ></m-form></div>-->
                            <div class="date-wrap">
                                <el-form-item :label="salesDate.label" class="form-item-wrap" :prop="salesDate.field_id">
                                    <m-form-item :field="salesDate" class="item-wrap" :value="salesDateValue" @m-change.self="handleDateChange"/>
                                </el-form-item>
                            </div>

                        </div>
                        <m-charts :options="lineChart"></m-charts>
                    </div>
                </el-col>
            </el-row>
            </el-scrollbar>
        </div>
    </el-container>
</template>

<script setup>
    import mCharts from '@/components/common/Charts/Charts'
    import mForm from '@/components/common/Form/Form'
    import mFormItem from '@/components/common/Form/FormItem'
    import mCard from './component/Card'
    import {getOrderCountByDay,getOrderCountByHour,getOrderCountByMonth,getAllOrderCount} from "../../request/api/basicData";
    import {getWeekFirstDate,getWeekLastDate,crtTimeFtt,getMonthFirstDate,getMonthLastDate,getQuarterFirstDate,getQuarterLastDate,getPrevDay,getNextDay} from "../../utils/utils";
    import {ref,reactive,onMounted} from 'vue';

    let loading = ref(false),
      chartLoading = ref(false);

    let card = ref([
        {
          title: '销量',
          totalText: '总计销量',
          col: 24,
          field_id: 'total',
          showYesterday: false
        },
        {
          title: '已支付订单量',
          totalText: '总计已支付订单量',
          col:12,
          field_id: 'paid_count',
          showYesterday: true
        },
        {
          title: '未支付订单量',
          totalText: '总计未支付订单量',
          col: 12,
          field_id: 'unpaid_count',
          showYesterday: true
        },
        /*{
          title: '收入',
          totalText: '总计收入',
          col: 8,
          field_id: 'applying_refund_count'
        },*/
      ]),
      cardData = ref({});

    let lineChart = reactive({
      title: '销量',
      category: [],
      source: [
        ['product','已支付订单量','未支付订单量'],
      ],
      type: 'line',
      xAxis: true
    }),
    salesRadio = ref('今天'),
    salesDate = ref({
      field_id: 'salesDate',
      label: '日期范围',
      type: 'daterange',
      dateFormat: 'YYYY-MM-DD',
      col: 4
    }),salesDateValue = ref('');

    const handleRadioChange = function (val) {
      chartLoading.value = true;
      let source = [['product','已支付订单量','未支付订单量']],
        start,end,type;
      switch (val) {
        case '今天':
          start = crtTimeFtt(new Date());
          type = 'hour';
          break;
        case '本周':
          start = crtTimeFtt(getWeekFirstDate())
          end = crtTimeFtt(getWeekLastDate())
          type = 'day';
          break;
        case '本月':
          start = crtTimeFtt(getMonthFirstDate())
          end = crtTimeFtt(getMonthLastDate());
          type = 'day';
          break;
        case '本季':
          start = crtTimeFtt(getQuarterFirstDate(),'YYYYMM')
          end = crtTimeFtt(getQuarterLastDate(),'YYYYMM');
          type = 'month';
          break;
      }
      getOrderCount(start,end,type).then(arr =>{
        chartLoading.value = false;
        source = [...source,...arr];
        lineChart.source = source
        salesDateValue.value = []
      })
    }
    const handleDateChange = function (val) {
      if (val){
        chartLoading.value = true;
        salesRadio.value = '';
        let date = val.salesDate;
        if (date){
          let type = 'day'
          if (date[0] === date[1]){
            type = 'hour'
          }
          getOrderCount(date[0],date[1],type).then(arr =>{
            chartLoading.value = false;
            lineChart.source = [['product','已支付订单量','未支付订单量'],...arr];
            salesRadio.value = '';
          })
        }
      }
    }
    function getOrderCount(start,end,type) {
      return new Promise(async resolve => {
        let arr = [];
        if (type === 'hour'){
          await getOrderCountByHour(start).then(res => {
            if (res.errcode !== 0) return;
            let data = res.row || [];
            data.forEach((item,index) => {
              let {hour,paid_count,unpaid_count} = item;
              arr.push([hour + '',paid_count, unpaid_count])
            });
          });
        }
        if (type === 'day') {
          await getOrderCountByDay(start,end).then(res => {
            if (res.errcode !== 0) return;
            let data = res.row || [];
            data.forEach((item,index) => {
              let {date,paid_count,unpaid_count} = item;
              arr.push([date,paid_count, unpaid_count])
            });
          });
        }
        if (type === 'month'){
          await getOrderCountByMonth(start,end).then(res => {
            if (res.errcode !== 0) return;
            let data = res.row || [];
            data.forEach((item,index) => {
              let {month,paid_count,unpaid_count} = item;
              arr.push([month,paid_count, unpaid_count])
            });
          });
        }

        resolve(arr);
      })
    }


    onMounted(() =>{
      loading.value = true;
      let today = crtTimeFtt(new Date()),
        yesterday = crtTimeFtt(getPrevDay());


      //获取昨日和今日图表分析增长比
      let pm = new Promise(resolve => {
        getAllOrderCount().then(res => {
          if (res.errcode !== 0) {
            resolve();
            return
          }
          let totalData = res.row[0];
          getOrderCountByDay(yesterday,today).then(res => {
            resolve();
            if (res.errcode !== 0) return;
            let data = res.row || [],
              yesterdayData = data[0],
              todayData = data[1],
              // fields = ['failure_count','paid_count','refund_count','unpaid_count','applying_refund_count'],
              fields = ['paid_count','unpaid_count',],  //界面中只显示了这两个的图表，所以只统计这两个数据
              obj = {},
              total = 0;
            fields.forEach(item =>{
              let _yesterday = yesterdayData[item] || 0,
                _today = todayData[item] || 0,
                compare = _today - _yesterday,
                percent = (_today && _yesterday && compare)  ? ( compare/_yesterday *100).toFixed(2) : 0;
              // total += _today;  //统计今日所有销量即所有数相加
              obj[item] = {
                yesterday: _yesterday,
                today: _today,
                compare,
                percent,
                total: totalData[item] || 0
              }
            })
            //今日总销量 = 已支付 + 申请退票中的订单
            obj.total = {
              today: (todayData.paid_count || 0) +(todayData.applying_refund_count || 0),
              total: (totalData.paid_count || 0) +(totalData.applying_refund_count || 0)
            }
            cardData.value = obj;
          });
        })
      }),
        pm1 = new Promise(resolve => {
          //获取今日销量图表
          getOrderCount(today,'','hour').then(arr => {
            lineChart.source = [['product','已支付订单量','未支付订单量'],...arr];
            resolve();
          })
        });
      Promise.all([pm,pm1]).then(() => {
        loading.value = false;
      })

    })
</script>

<style scoped lang="less">
.layout-container{
    height: 100%;
    /*background: #ffffff;*/
    .wrap{
        width: 100%;
        .row{
            .col{
                margin-bottom: 20px;
            }
            .card-wrap{
                width: 100%;
                background: #ffffff;
            }
            .chart-wrap{
                width: 100%;
                height: 400px;
                background: #ffffff;
                padding: 16px;
                box-sizing: border-box;
                .tool-wrap{
                    width: 100%;
                    /*display: flex;*/
                    .radio-wrap{
                        display: inline-block;
                        margin-right: 16px;
                    }
                    .date-wrap{
                        width: 400px;
                        display: inline-block;
                    }
                }
            }
        }
    }
}
</style>
